﻿<template>
  <div class="busGoods-container">
    <el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
        <el-form :model="queryParams" ref="queryForm" :inline="true">
            <el-form-item label="编码">
                <el-input v-model="queryParams.goodCode" clearable="" placeholder="请输入编码" />

            </el-form-item>
            <el-form-item label="名称">
                <el-input v-model="queryParams.goodName" clearable="" placeholder="请输入名称" />

            </el-form-item>
            <el-form-item label="单价">
                <el-input v-model="queryParams.unitAmount" clearable="" placeholder="请输入单价" />

            </el-form-item>
            <el-form-item label="量纲(单位)">
                <el-select clearable="" filterable="" v-model="queryParams.unit" placeholder="请选择量纲(单位)">
                    <el-option v-for="(item,index) in sysClassDropdownList" :key="index" :value="item.value" :label="item.label" />

                </el-select>

            </el-form-item>
            <el-form-item label="商品标签">
                <el-select clearable="" filterable="" v-model="queryParams.flag" placeholder="请选择商品标签">
                    <el-option v-for="(item,index) in sysClassFlagDropdownList" :key="index" :value="item.value" :label="item.label" />

                </el-select>

            </el-form-item>
            <el-form-item label="物料编码">
                <el-select clearable="" filterable="" v-model="queryParams.productCode" placeholder="请选择物料编码">
                    <el-option v-for="(item,index) in busProductDropdownList" :key="index" :value="item.value" :label="item.label" />

                </el-select>

            </el-form-item>
            <el-form-item label="物料名称">
                <el-input v-model="queryParams.productName" clearable="" placeholder="请输入物料名称" />

            </el-form-item>
            <el-form-item label="是否上架">
                <el-select clearable="" v-model="queryParams.online" placeholder="请选择是否上架">
                    <el-option v-for="(item,index) in getonlineData" :key="index" :value="item.code" :label="item.value" />

                </el-select>

            </el-form-item>
            <el-form-item label="是否停用">
                <el-select clearable="" v-model="queryParams.isDelete" placeholder="请选择是否停用">
                    <el-option v-for="(item,index) in getonlineData" :key="index" :value="item.code" :label="item.value" />

                </el-select>

            </el-form-item>
            <el-form-item label="商品描述">
                <el-input v-model="queryParams.remark" clearable="" placeholder="请输入商品描述" />

            </el-form-item>
            <el-form-item>
                <el-button-group>
                    <el-button type="primary" icon="ele-Search" @click="handleQuery" v-auth="'busGoods:page'"> 查询 </el-button>
                    <el-button icon="ele-Refresh" @click="() => queryParams = {}"> 重置 </el-button>

                </el-button-group>

            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="ele-Plus" @click="openAddBusGoods(0)" v-auth="'busGoods:add'"> 新增 </el-button>

            </el-form-item>
            <el-form-item>
                <el-button type="primary"  @click="downloadFile" v-auth="'busGoods:page'"> 下载模版 </el-button>

            </el-form-item>
            <el-form-item>
                <el-button type="primary"  @click="openUploadDialog" v-auth="'busGoods:page'"> 批量导入 </el-button>

            </el-form-item>

        </el-form>
    </el-card>
    <el-card class="full-table" shadow="hover" style="margin-top: 8px">
        <el-table :data="tableData"
                  style="width: 100%"
                  v-loading="loading"
                  tooltip-effect="light"
                  row-key="id"
                  border="">
            <el-table-column type="index" label="序号" show-overflow-tooltip="" width="55" align="center" />
            <el-table-column prop="goodCode" label="编码" show-overflow-tooltip="" />
            <el-table-column prop="goodName" label="名称" show-overflow-tooltip="" />
            <el-table-column prop="unitName" label="量纲(单位)" show-overflow-tooltip=""> </el-table-column>
            <el-table-column prop="flagText" label="商品标签" show-overflow-tooltip=""> </el-table-column>
            <el-table-column prop="supName" label="供货商" show-overflow-tooltip=""> </el-table-column>
            <el-table-column prop="attributeInfo" label="属性" show-overflow-tooltip="" />
            <el-table-column prop="productCode" label="物料编码" show-overflow-tooltip=""> </el-table-column>
            <el-table-column prop="productName" label="物料名称" show-overflow-tooltip="" >
                <template #default="scope" >
                    <span>{{scope.row.productName}}</span>
                </template>
            </el-table-column>
            <el-table-column prop="onlineName" label="是否上架" show-overflow-tooltip="" />
            <el-table-column prop="remark" label="商品描述" show-overflow-tooltip="" />
            <el-table-column prop="isDeleteName" label="是否停用" show-overflow-tooltip="" />
            <el-table-column label="操作" width="200" align="center" fixed="right" show-overflow-tooltip="" v-if="auth('busGoods:edit') || auth('busGoods:delete')">
                <template #default="scope">
                    <el-button icon="ele-Edit" size="small" text="" type="primary" @click="openEditBusGoods(scope.row,1)" v-auth="'busGoods:edit'"> 编辑 </el-button>
                    <el-button icon="ele-Memo" size="small" text type="primary" @click="openDictDataDialog(scope.row)" v-auth="'busGoods:page'"> 属性 </el-button>
                    <el-button icon="ele-Delete" size="small" text="" type="primary" @click="delBusGoods(scope.row)" v-auth="'busGoods:delete'"> 停用 </el-button>
                </template>
            </el-table-column>
        </el-table>
      <el-pagination
				v-model:currentPage="tableParams.page"
				v-model:page-size="tableParams.pageSize"
				:total="tableParams.total"
				:page-sizes="[10, 20, 50, 100]"
				small=""
				background=""
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				layout="total, sizes, prev, pager, next, jumper"/>
      <editDialog ref="editDialogRef"  :title="editBusGoodsTitle"  @reloadTable="handleQuery" :goodCode="goodCode"  :productCode="productCode"/>
      <dictDataDialog ref="dictDataDialogRef" :isShowDialog="isShowDialog" />
    </el-card>

    <el-dialog v-model="state.dialogUploadVisible" :lock-scroll="false" draggable width="400px">
			<template #header>
				<div style="color: #fff">
					<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle"> <ele-UploadFilled /> </el-icon>
					<span> 上传文件 </span>
				</div>
			</template>
			<div>
				<el-upload ref="uploadRef" drag :auto-upload="false" :limit="1" :file-list="state.fileList"  action="" :on-change="handleChange" accept=".jpg,.png,.bmp,.gif,.txt,.pdf,.xlsx,.docx">
					<el-icon class="el-icon--upload">
						<ele-UploadFilled />
					</el-icon>
					<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
					<template #tip>
						<div class="el-upload__tip">请上传大小不超过 10MB 的文件</div>
					</template>
				</el-upload>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="state.dialogUploadVisible = false">取消</el-button>
					<el-button type="primary" @click="uploadFile">确定</el-button>
				</span>
			</template>
		</el-dialog>

  </div>
</template>

<script lang="ts" setup="" name="busGoods">
  import { reactive, ref } from "vue";
  import { ElMessageBox, ElMessage ,ElIcon, UploadInstance} from "element-plus";
  import { auth } from '/@/utils/authFunction';
  //import { formatDate } from '/@/utils/formatTime';

  import editDialog from '/@/views/main/busGoods/component/editDialog.vue'
  import { pageBusGoods, deleteBusGoods, getSysClassDropdown, GetSysClassFlagDropdown, getBusProductDropdown } from '/@/api/main/busGoods';
  import { upLoadFileGoods, importFileGoods,downloadFileGoods} from '/@/api/main/busGoods';
  import { getDictDataList } from '/@/api/system/admin';
  import GoodAttributeDialog from '/@/views/main/busGoods/component/goodAttributeDialog.vue';
  import dictDataDialog from './component/goodAttributeDialog.vue';
  import {  getProductAttrListFn,getProductAttrLstFn } from '/@/api/main/BusGoodsDialog';
import { downloadByUrl } from "/@/utils/download";
import { SysFile } from "/@/api-services";

const uploadRef = ref<UploadInstance>();
const state = reactive({
	loading: false,
	fileData: [] as Array<SysFile>,
	queryParams: {
		fileName: undefined,
		startTime: undefined,
		endTime: undefined,
	},
	tableParams: {
		page: 1,
		pageSize: 10,
		total: 0 as any,
	},
	dialogUploadVisible: false,
	dialogPdfVisible: false,
	fileList: [] as any,
	pdfUrl: '',
});

  const dictDataDialogRef = ref<InstanceType<typeof GoodAttributeDialog>>();
  const isShowDialog = ref(false);

    const getonlineData = ref<any>([]);
    const getisDeleteData = ref<any>([]);

    const editDialogRef = ref();
    const loading = ref(false);
    const tableData = ref<any>
      ([]);
      const queryParams = ref<any>
        ({});
        const tableParams = ref({
        page: 1,
        pageSize: 10,
        total: 0,
        });
        const editBusGoodsTitle = ref("");
        const goodCode = ref('');
        const productCode = ref('');

        // 查询操作
        const handleQuery = async () => {
        loading.value = true;
        var res = await pageBusGoods(Object.assign(queryParams.value, tableParams.value));
        tableData.value = res.data.result?.items ?? [];
        tableParams.value.total = res.data.result?.total;
        loading.value = false;
            getonlineData.value = await dictTypeDataList('data_yes_no');
            getisDeleteData.value = await dictTypeDataList('data_yes_no');
        };

        // 打开新增页面
        const openAddBusGoods = (isUpdate:any) => {
            handleQuery();
        editBusGoodsTitle.value = '添加商品管理';
        editDialogRef.value.openDialog({});
        };

        // 打开编辑页面
        const openEditBusGoods = (row: any,isUpdate:any) => {
            handleQuery();
        editBusGoodsTitle.value = '编辑商品管理';
        editDialogRef.value.openDialog(row,isUpdate);

        getProductAttrListFn(row.goodCode);
         getProductAttrLstFn(row.productCode);
        };
        //明细
        const openDictDataDialog = (row: any) => {
	        // console.log(row);
	        dictDataDialogRef.value?.openDialog(row);
        };
        // 删除
        const delBusGoods = (row: any) => {
        ElMessageBox.confirm(`确定要删除吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        })
        .then(async () => {
        await deleteBusGoods(row);
        handleQuery();
        ElMessage.success("删除成功");
        })
        .catch(() => {});
        };

        // 改变页面容量
        const handleSizeChange = (val: number) => {
        tableParams.value.pageSize = val;
        handleQuery();
        };

        // 改变页码序号
        const handleCurrentChange = (val: number) => {
        tableParams.value.page = val;
        handleQuery();
        };

        const sysClassDropdownList = ref<any>([]); 
const getSysClassDropdownList = async () => {
    let list = await getSysClassDropdown();
    sysClassDropdownList.value = list.data.result ?? [];
};
getSysClassDropdownList();

const sysClassFlagDropdownList = ref<any>([]); 
const getSysClassFlagDropdownList = async () => {
    let list = await GetSysClassFlagDropdown();
    sysClassFlagDropdownList.value = list.data.result ?? [];
};
getSysClassFlagDropdownList();

const busProductDropdownList = ref<any>([]); 
const getBusProductDropdownList = async () => {
    let list = await getBusProductDropdown();
    busProductDropdownList.value = list.data.result ?? [];
};
getBusProductDropdownList();


const dictTypeDataList = async (val: any) => {
      let list = await getDictDataList(val);
      return list.data.result ?? [];
    };
// 打开上传页面
const openUploadDialog = () => {
	state.fileList = [];
	state.dialogUploadVisible = true;
};

// 通过onChanne方法获得文件列表
const handleChange = (file: any, fileList: []) => {
	state.fileList = fileList;
};

// 上传
const uploadFile = async (res: any) => {

	if (state.fileList.length < 1) return;
    let fd=new FormData()
    fd.append('file', state.fileList[0].raw as any)
	await importFileGoods(fd);

	handleQuery();
	ElMessage.success('批量导入成功');
	state.dialogUploadVisible = false;
};

// 下载
const downloadFile = async (row: any) => {

    var fileUrl =await downloadFileGoods();

	// let fileUrl   = await upLoadFileGoods();
    console.log(fileUrl);
    // downloadByUrl({ url: fileUrl.data.result });
    
	// window.location.href =list.data.result;

// console.log(fileUrl);
    const blob = new Blob([fileUrl.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
                    const fileName = '商品物料模版.xlsx'
                    if ('download' in document.createElement('a')) { // 非IE下载
                        const elink = document.createElement('a')
                        elink.download = fileName
                        elink.style.display = 'none'
                        elink.href = URL.createObjectURL(blob)
                        document.body.appendChild(elink)
                        elink.click()
                        URL.revokeObjectURL(elink.href) // 释放URL 对象
                        document.body.removeChild(elink)
                    } 
                    // else { // IE10+下载
                        // navigator.msSaveBlob(blob, fileName)
                    // }
};

handleQuery();


</script>


